package com.itheima.controller;


import ch.qos.logback.core.joran.util.beans.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.entity.DownloadData;
import com.itheima.entity.Orders;
import com.itheima.service.IOrdersService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@RestController
@RequestMapping("/order")
@Slf4j
public class OrdersController {

//    注入业务层
    @Autowired
    private IOrdersService ordersService;

//      订单相关需求
//      接口一：去支付，生成订单
//      请求url地址：/order/submit
//      请求方式：POST
//      请求参数：JSON
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
      ordersService.submit(orders);
        return R.success("购买成功");
    }

//          接口二：分页查询订单
//          请求url地址：/order/userPage?page=1&pageSize=5
//          请求方式：GET
//          请求参数：?page=1&pageSize=5

    @GetMapping("/userPage")
    public R<Page<Orders>> listPage(Integer page, Integer pageSize){
        Page<Orders> page1= new Page(page,pageSize);
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getUserId, BaseContext.getCurrentId());
        wrapper.orderByDesc(Orders::getOrderTime);
        Page<Orders> ordersPageList = ordersService.page(page1, wrapper);
        return R.success(ordersPageList);
    }

//    后台订单分页查询
    @GetMapping("/page")
    public R<Page<Orders>> listPage2(Integer page, Integer pageSize, String number,
                                     @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") LocalDateTime beginTime,
                                     @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") LocalDateTime endTime){
        log.info("beginTime:{}",beginTime);
        log.info("endTime:{}",endTime);
        Page<Orders> page1= new Page(page,pageSize);
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Orders::getOrderTime);
        wrapper.like(StringUtils.isNotEmpty(number),Orders::getNumber,number);
        if (beginTime!=null||endTime!=null){
            wrapper.between(Orders::getOrderTime,beginTime,endTime);
        }
        Page<Orders> ordersPageList = ordersService.page(page1, wrapper);
        return R.success(ordersPageList);


    }

//    订单状态修改操作
    @PutMapping
    public R<String> status(@RequestBody Orders orders){
        LambdaUpdateWrapper<Orders> wrapper =new  LambdaUpdateWrapper();
        wrapper.eq(Orders::getId,orders.getId());
        orders.setStatus(4);
        ordersService.update(orders,wrapper);
        return R.success("修改成功");
    }

//      接口二：订单明细中新增一个Excel导出功能
//      请求url地址：/order/export
//      请求方式：GET
//      请求参数：无
//      响应结果【格式统一】：excel文件内容



    @GetMapping("/export")
    public void download(HttpServletResponse response) throws IOException {
//        获取页面的数据
        List<Orders> list = ordersService.list();
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("订单明细", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), DownloadData.class).sheet("模板").doWrite(list);
    }




}
